package com.ewhale.feitengguest.utils;

import com.luck.picture.lib.entity.LocalMedia;
import com.simga.library.http.Event;
import com.simga.library.http.HttpHelper;
import com.simga.library.http.Request;
import com.simga.library.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import okhttp3.RequestBody;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;

/**
 * 服务器上传文件
 * PackageName : cn.ewhale.huaxinebought.utils
 * Author : SimGa Liu
 * Date : 2017/07/25
 * Time : 14:42
 */
public class UpLoadImageUtils {
    //上传单个文件
    public static Request getRequest(final CallBack callBack) {
        Request request = new Request() {
            @Override
            public <T> void onNext(int postCode, T result, Object data) {
                super.onNext(postCode, result, data);
                if (postCode == 1) {
                    callBack.complete(result.toString());
                }
            }
            @Override
            public void onError(int postCode, Object data, Throwable e) {
                super.onError(postCode, data, e);
                callBack.fail();
                LogUtil.e(LogUtil.TAG,e.toString());
            }
        };
        return request;
    }


    public static void upLoad(List<LocalMedia> path, onCallBackList callBack) {
        doSubmit(path, callBack);
    }

    interface ImageApi {
        /**
         * 图片
         *
         * @param image
         * @return
         */
        @Multipart
        @POST("上传图片地址")
        Observable<String> upLoadFile(
                @Part("file\"; filename=\"image.jpg") RequestBody image);

    }

    public static void doSubmit(List<LocalMedia> path, final onCallBackList onCallBackList) {
        final List<RequestBody> bodys = ImagePart.getPart(path);
        final List<String> urls = new ArrayList<>();
        for (RequestBody body : bodys) {
            getRequest(new CallBack() {
                @Override
                public void complete(String key) {
                    urls.add(key);
                    if (urls.size() == bodys.size()) {
                        onCallBackList.complete(urls);
                    }
                }
                @Override
                public void fail() {
                    onCallBackList.fail();
                }
            }).request(1, HttpHelper.apiHttp.getService(ImageApi.class).
                    upLoadFile(body), null, Event.DESTROY);
        }
    }
    public interface CallBack {
        void complete(String key);
        void fail();
    }

    public interface onCallBackList {
        void complete(List<String> key);
        void fail();
    }
}
